package com.hzxgs.tracelogstarter.trace;

import com.hzxgs.tracelogstarter.properties.TraceProperties;
import com.hzxgs.tracelogstarter.util.TraceUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.protocol.HttpContext;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Component
@ConditionalOnClass(value = {HttpRequestInterceptor.class})
@Order(TraceUtils.FILTER_ORDER)
@Slf4j
public class HttpClientTraceInterceptor implements HttpRequestInterceptor {

    @Resource
    private TraceProperties traceProperties;

    @Override
    public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException {
        if (traceProperties.getEnable()) {
            try {
                String traceId = httpRequest.getFirstHeader(TraceUtils.TRACE_ID_HEADER).getValue();
                if (StringUtils.isBlank(traceId)) {
                    TraceUtils.addTrace();
                } else {
                    String spanId = httpRequest.getFirstHeader(TraceUtils.SPAN_ID_HEADER).getValue();
                    TraceUtils.putTrace(traceId, spanId);
                }
                httpRequest.addHeader(TraceUtils.TRACE_ID_HEADER, TraceUtils.getTraceId());
                httpRequest.addHeader(TraceUtils.SPAN_ID_HEADER, TraceUtils.getSpanId());
            } catch (Exception e) {
                log.info("httpClient设置透传TraceId失败");
                e.printStackTrace();
            } finally {
                TraceUtils.removeTrace();
            }
        }
    }
}
